package com.dcms.power.aspect;


import com.dcms.admin.bean.Log;
import com.dcms.admin.bean.User;
import com.dcms.admin.service.ILogService;
import com.dcms.power.annotation.ArchivesLog;
import com.dcms.util.IPUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Aspect
@Component
public class ArchivesLogAspect {

    @Autowired
    private HttpServletRequest request = null;
    @Autowired
    private HttpSession session;
    @Autowired
    private ILogService logService;

    private static Log log = new Log();

    @Around("within(com.dcms..*) && @annotation(archivesLog)")
    public Object around(ProceedingJoinPoint pjd, ArchivesLog archivesLog) throws Throwable {
        log.setLogId(null);
        log.setCtime(new Date());
        long startTime=System.currentTimeMillis();

        //类名
        String className = pjd.getTarget().getClass().getName();
        log.setClasz(className);

        //方法名
        String methodName = pjd.getSignature().getName();
        log.setMethod(methodName);

        //获取请求参数
        Object[] params = pjd.getArgs();
        String paramsStr = "";
        for(Object param:params) {
            paramsStr += (param + ",");
        }
        log.setParams(paramsStr);

        //请求地址
        String uri = request.getRequestURI();
        log.setUri(uri);

        //IP
        String host = IPUtil.getIpAddr(request);
        log.setHost(host);

        //###################上面代码为方法执行前#####################

        //执行方法，获取返回参数
        Object result  = pjd.proceed();

        //###################下面代码为方法执行后#####################

        String message = archivesLog.message();
        log.setMessage(message);

        //操作人
        User thisUser = (User)session.getAttribute(User.CURRENT_LOGIN_USER);
        if (thisUser != null){
            int userId = thisUser.getUserId();
            log.setUserId(userId);
        }

        //结束时间
        long endTime=System.currentTimeMillis();
        float excTime=(float)(endTime-startTime)/1000;
        log.setEndtime(new Date());
        log.setExctime(excTime);

        //录入数据库
        logService.insertSelective(log);

        return result;
    }


}